<template>
  <div id="codelogin">
    <div class="reg">
      <group title="" class="weui-cells_form">
        <x-input v-model="formItem.phone" type="tel" title="手机号" class="weui-vcode" placeholder="请输入手机号码" :max="11" :show-clear="false">
          <x-button :disabled="disabled" slot="right" type="primary" mini @click.native="sendCode">{{codebtn}}</x-button>
        </x-input>
        <x-input v-model="formItem.code" type="tel" title="验证码" class="weui-vcode" placeholder="请输入短信验证码" :max="4"></x-input>
      </group>
    </div>
    <div style="margin: 0.3rem 0.2rem 0.2rem 0.2rem">
      <x-button type="primary" :show-loading="loading" action-type="button" @click.native="handleReg">{{btn}}</x-button>
    </div>
  </div>
</template>
<script>
  import PubHeader from '../components/PubHeader.vue'
  import $config from '../libs/config'
  import { checkTel } from '../libs/fn'
  export default{
    components: {
      PubHeader
    },
    mounted() {
      const u = navigator.userAgent;
      const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      this.formItem.os = isiOS ? 'ios': 'android'
    },
    created() {
      var regmap, geolocation;
      //加载地图，调用浏览器定位服务
      regmap = new AMap.Map('container', {
        resizeEnable: true
      });
      regmap.plugin('AMap.Geolocation', () => {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：无穷大
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          buttonPosition:'RB'
        });
        regmap.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', (data) => {
          const lnglatXY = [data.position.getLng(), data.position.getLat()]
          this.formItem.city_code = data.addressComponent.adcode
          this.formItem.lng = data.position.getLng()
          this.formItem.lat = data.position.getLat()
          var geocoder = new AMap.Geocoder({
            radius: 500,
            extensions: "all"
          });
          geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              this.formItem.location =  result.regeocode.formattedAddress
            }
          });
        });
        AMap.event.addListener(geolocation, 'error', (data) => {
          AMap.plugin('AMap.CitySearch',() => {//异步
            let citysearch = new AMap.CitySearch();
            //自动获取用户IP，返回当前城市
            citysearch.getLocalCity((status, result) => {
              if (status === 'complete' && result.info === 'OK') {
                if (result && result.city && result.bounds) {
                  this.formItem.city_code = result.adcode
                }
              }
            })
          })
        });
      });

    },
    data() {
      return {
        loading: false,
        disabled: false,
        btn: '登录',
        codebtn: '发送验证码',
        formItem: {
          login_type: 2,
          phone: '',
          password: '',
          client: $config.client_type,
          device: $config.device_type,
          version: $config.version,
          device_name: 'wap',
          os: '',
          city_code: '',
          lng: '',
          lat: '',
          location: ''
        }
      }
    },
    methods: {
      sendCode() {
        if(!checkTel(this.formItem.phone)) {
          this.$vux.toast.text('手机号码格式不正确', 'middle')
          return false
        }
        this.disabled = true
        this.codebtn = '正在发送...'
        this.$http.post($config.host + '/api/Userbase/getMessage', qs.stringify({
          phone: this.formItem.phone,
          type: 7
        })).then((res) => {
          const {code, msg} = res.data
          if(code == 1) {
            let i = $config.sendCodeTimer
            let timer = setInterval(() => {
              i--
              this.codebtn = i+'s发送成功'
              if(i <= 0) {
                clearInterval(timer)
                this.disabled = false
                this.codebtn = '重新发送'
              }
            }, 1000)
          } else {
            this.disabled = false
            this.codebtn = '获取验证码'
            this.$vux.toast.text(msg, 'middle')
          }
        }).catch((err) => {
          this.disabled = false
          this.codebtn = '获取验证码'
          this.$vux.toast.text($config.errMsg, 'middle')
        })


      },
      handleReg() {
        if(!checkTel(this.formItem.phone)) {
          this.$vux.toast.text('手机号码格式不正确', 'middle')
          return false
        }
        if(this.formItem.code.length < 4) {
          this.$vux.toast.text('请填写4位验证码', 'middle')
          return false
        }
        this.loading = true
        this.$http.post($config.host + '/api/Userbase/login', qs.stringify(this.formItem))
          .then((res) => {
            const {code, data, msg} = res.data
            if(code == 1) {
              let user = {
                uid: data.uid,
                phone: data.phone,
                status: data.status,
                token: data.token,
                verify_company: data.verify_company,
                verify_card: data.verify_card,
                verify_car: data.verify_car,
                verify_num: data.verify_num,
                level: data.level,
                fid: data.fid,
                //city_code: this.formItem.city_code,
                city_code: '420502',
                order_pai: data.order_pai,
                lng: '',
                lat: '',
                identity: data.identity,
                location: ''
              }
              this.$store.commit('setUserInfo', user)

              //将登录数据保存在localStorage中
              window.localStorage.user = JSON.stringify(user)
              // 跳转到登录前的页面
              let redirect = decodeURIComponent(this.$route.query.redirect || '/')
              this.$router.push({
                path: redirect
              })
            } else {
              this.$vux.toast.text(msg, 'middle')
            }
            this.loading = false
          })
          .catch((error) => {
            this.$vux.toast.text($config.errMsg, 'middle')
            this.loading = false
          })
      }
    },
    beforeRouteLeave(to, from, next) {
      this.formItem = {
        login_type: 2,
        phone: '',
        password: '',
        client: $config.client_type,
        device: $config.device_type,
        version: $config.version,
        device_name: 'wap',
        os: '',
        city_code: '',
        lng: '',
        lat: '',
        location: ''
      }
      next()
    }
  }
</script>
<style scoped>
  .reg{
    margin: 0.2rem;
    background: #fff;
    height: auto;
    box-shadow: 0px 0px 0.15rem rgba(0, 0, 0, 0.07);
  }
</style>
